package com.ehome.poct.core.controller;

import cn.hutool.json.JSONUtil;
import com.ehome.poct.core.api.constant.enums.ScanTypeEnums;
import com.ehome.poct.core.api.dto.groups.ValidationGroups;
import com.ehome.poct.core.api.dto.order.TestOrderItemDTO;
import com.ehome.poct.core.api.dto.order.UnificationPayReqDTO;
import com.ehome.poct.core.api.dto.order.UnificationShareAccountReqDTO;
import com.ehome.poct.core.api.feign.TestOrderUnificationPayProxyClient;
import com.ehome.poct.core.api.virtual.TestOrderUnificationPayService;
import com.ehome.poct.core.api.vo.order.UnificationPayVO;
import com.ehome.poct.core.api.vo.order.UnificationShareAccountVO;
import com.ehome.poct.core.utils.ValidateUtil;
import com.ehome.web.annotation.RequestLog;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @auther: kuiba.peng
 * @date: 2022/11/21 21:04
 * @description:
 */
@RestController
@RequestMapping("/orderUnificationPay")
@AllArgsConstructor
@Slf4j
@ApiModel("统一支付入口")
public class TestOrderUnificationPayController implements TestOrderUnificationPayProxyClient {

    private final TestOrderUnificationPayService unificationPayService;

    @ApiOperation("保存分账信息")
    @Override
    @RequestLog
    public UnificationShareAccountVO saveShareAccount(@RequestBody @Valid UnificationShareAccountReqDTO reqDTO) {
        log.info("saveShareAccount request url:[{}] , params:[{}]", "/orderUnificationPay/saveShareAccount", JSONUtil.toJsonStr(reqDTO));
        List<TestOrderItemDTO> orderItemDTOList = reqDTO.getOrderItemDTOList()
                .stream()
                // 金额不能等于空 并且不小于0
                .filter(orderItemDTO -> Objects.nonNull(orderItemDTO.getFee()) && BigDecimal.ZERO.compareTo(orderItemDTO.getFee()) < 0)
                .collect(Collectors.toList());
        reqDTO.setOrderItemDTOList(orderItemDTOList);
        return unificationPayService.saveShareAccount(reqDTO);
    }

    @ApiOperation("唤起支付")
    @Override
    @RequestLog
    public UnificationPayVO pay(UnificationPayReqDTO payReqDTO) {
        ScanTypeEnums scanType = payReqDTO.getScanType();
        log.info("pay request url:[{}] , params:[{}]", "/orderUnificationPay/pay", JSONUtil.toJsonStr(payReqDTO));
        Class<?> groupClass = ValidationGroups.SecondGroups.class;
        if (ScanTypeEnums.B2C.equals(scanType)) {
            groupClass = ValidationGroups.FirstGroups.class;
        }
        ValidateUtil.validate(payReqDTO, groupClass);
        return unificationPayService.pay(payReqDTO);
    }
}
